import { defineBoot } from '#q-app/wrappers'
import { LoadingBar } from 'quasar'
import { userStores } from 'src/stores/user-stores'
import { isInIframe } from 'src/utils/utils.js'

const loginPath = '/login'
const whiteList = [loginPath, '/MapMonitoring']
export default defineBoot(({ router }) => {
  router.beforeEach((to, from, next) => {
    !isInIframe() && !LoadingBar.isActive && LoadingBar.start()
    if (to.query?.login === 'non') userStores().LOGOUT && userStores().LOGOUT()
    const { LoginByName, token = '', userInfo = {} } = userStores()
    if (['', 'undefined', 'null'].includes(token) || !userInfo.id) {
      if (to.query && to.query?.login === 'non') {
        const { loginName = 'SYS', password = 'agv1234' } = to.query
        const loginForm = { loginName, password, tenantId: window.IPConfig.TENANT_ID, getOSS: true }
        LoginByName(loginForm).then(async ({ done }) => {
          await next({ path: to.path })
          done && done()
        }).catch(async () => await next({ path: loginPath }))
        return
      }
      if (!whiteList.includes(to.path)) return next({ path: loginPath })
      return next()
    }
    if (to.path === loginPath) return next({ path: '/dashboard/console' })
    next()
  })
  router.afterEach(() => LoadingBar.stop())
})